/*
 * @Author: 精金电子 maicent@qq.com
 * @Date: 2025-03-06 10:28:41
 * @LastEditors: 精金电子 maicent@qq.com
 * @LastEditTime: 2025-03-06 15:44:43
 * @FilePath: \gis-web\src\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router, { constantRoutes } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

// 添加全局错误处理
window.addEventListener('error', (event) => {
  console.error('全局错误:', event.error)
  // Message.error('系统发生错误，请刷新页面或联系管理员')
})

// 添加未捕获的Promise错误处理
window.addEventListener('unhandledrejection', (event) => {
  console.error('未处理的Promise错误:', event.reason)
  Message.error('系统发生错误，请刷新页面或联系管理员')
})

router.beforeEach(async(to, from, next) => {
  try {
    // start progress bar
    NProgress.start()

    // set page title
    const title = to.meta && to.meta.title ? to.meta.title : ''
    document.title = getPageTitle(title)

    // determine whether the user has logged in
    const hasToken = getToken()
    if (hasToken) {
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
        NProgress.done()
      } else {
        const hasRoles = store.getters.roles && store.getters.roles.length > 0
        if (hasRoles) {
          next()
        } else {
          try {
            // get user info
            // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
            const { role } = await store.dispatch('user/getInfo')

            if (!role) {
              throw new Error('角色获取失败，请重新登录')
            }

            // generate accessible routes map based on roles
            const accessRoutes = await store.dispatch('permission/generateRoutes', [role])

            // dynamically add accessible routes
            router.options.routes = constantRoutes.concat(accessRoutes)

            // 检查路由配置是否正确
            if (!Array.isArray(accessRoutes)) {
              console.error('accessRoutes不是数组:', accessRoutes)
              throw new Error('路由配置错误')
            }

            router.addRoutes(accessRoutes)

            // hack method to ensure that addRoutes is complete
            // set the replace: true, so the navigation will not leave a history record
            next({ ...to, replace: true })
          } catch (error) {
            // remove token and go to login page to re-login
            await store.dispatch('user/resetToken')
            Message.error(error.message || '系统错误，请重新登录')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        }
      }
    } else {
      /* has no token*/
      console.log('无Token，检查白名单')
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        console.log('在白名单中，直接访问')
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        console.log('不在白名单中，重定向到登录页')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } catch (error) {
    console.error('路由守卫全局错误:', error)
    Message.error('系统错误，请刷新页面')
    next('/login')
    NProgress.done()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
